/**
 * 定时器管理
 */
import { StateType } from '@/common-typings';

class SetTimeoutManager {
  public setTimeoutQueue: any[] = [];

  public timeWorker: StateType = {};

  /**
   * 添加定时任务
   * @param id
   * @param cb
   */
  addSetTimeout(id: string, cb: Function) {
    if (!this.setTimeoutQueue.filter((item: StateType) => item.id === id).length) {
      this.setTimeoutQueue.push({ id, cb });
    }
    return this;
  }

  /**
   * 根据id清理定时任务
   * @param id
   */
  delSetTimeout(id: string) {
    this.setTimeoutQueue = this.setTimeoutQueue.filter(item => item.id !== id);
  }

  /**
   * 开始执行定时任务
   * @param id
   * @param time
   * @param once
   */
  startSetTimout(id: string, time = 1000, once = false): void {
    const currentSetTimeout = this.setTimeoutQueue.filter(item => item.id === id)[0];

    if (currentSetTimeout) {
      const execute = (fn: Function) => {
        if (this.timeWorker[id]) clearTimeout(this.timeWorker[id]);
        this.timeWorker[id] = setTimeout(() => {
          fn();
          if (!once) {
            execute(fn);
          }
        }, time);
      };
      execute(currentSetTimeout.cb);
    }
  }

  /**
   * 停止定时任务
   * @param id
   */
  stopSetTimeout(id: string) {
    if (!id) {
      this.setTimeoutQueue = [];
      Object.keys(this.timeWorker).forEach(key => {
        clearTimeout(this.timeWorker[key]);
        delete this.timeWorker[key];
      });
      return this;
    }
    this.setTimeoutQueue = this.setTimeoutQueue.filter(item => item.id !== id);
    Object.keys(this.timeWorker).forEach(key => {
      if (key === id) {
        clearTimeout(this.timeWorker[key]);
        delete this.timeWorker[key];
      }
    });
    return this;
  }

  static instance: any;

  static getInstance() {
    if (!this.instance) {
      this.instance = new SetTimeoutManager();
    }
    return this.instance;
  }
}

export default SetTimeoutManager.getInstance();
